package vip.sone.util;

import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;

import java.util.Base64;

public class EncodeUtil {
    /* ------------------------------ 普通算法 ---------------------------- */
    /* ------------------------------ 可以逆解 ---------------------------- */
    /**
     * Hex编解码
     */
    public static String encodeToHex(String origin) {
        return Hex.encodeToString(origin.getBytes());
    }
    public static String decodeHex(String hex) {
        return new String(Hex.decode(hex));
    }

    /**
     * Base64编解码
     */
    public static String encodeToBase64(String origin) {
        return Base64.getEncoder().encodeToString(origin.getBytes());
    }
    public static String decodeBase64(String base64) {
        return new String(Base64.getDecoder().decode(base64.getBytes()));
    }
    /* ------------------------------------------------------------------ */

    /* ------------------------------ 散列算法 ---------------------------- */
    /**
     * MD5加密
     * @param origin 原始数据
     * @param salt 盐
     * @param count 散列次数
     */
    public static String encodeToMD5(String origin, String salt, int count) {
        return new Md5Hash(origin, salt, count).toString();
    }
    public static String encodeToMD5(String origin, String salt) {
        return encodeToMD5(origin, salt, 1);
    }
    public static String encodeToMD5(String origin) {
        return encodeToMD5(origin, "", 1);
    }

    /**
     * SHA加密
     * @param algorithm 加密算法
     *                  SHA-1
     *                  SHA-512
     */
    /* ------------------------------------------------------------------ */
    public static String encodeToSHA(String algorithm, String origin, String salt, int count) {
        return new SimpleHash(algorithm, origin, salt, count).toString();
    }
    // 默认是"SHA-256"算法
    public static String encodeToSHA(String origin, String salt, int count) {
        return encodeToSHA("SHA-256", origin, salt, count);
    }
    public static String encodeToSHA(String origin, String salt) {
        return encodeToSHA(origin, salt, 1);
    }
    public static String encodeToSHA(String origin) {
        return encodeToSHA(origin, "", 1);
    }
}
